package com.ycl.service;

import com.alibaba.excel.util.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Date;

/**
 * @ClassName: GeneratedServiceImpl
 * @Package: Image_synthesis
 * @Description:
 * @Author: sen.yang@youhualin.com
 * @Date: 2021/12/21 11:32
 * @Copyright: 德慧信息技术有限公司
 */

@Service
public class GeneratedServiceImpl implements GeneratedService{
    @Value("${ycl.path}")
    private String path;

    @Override
    public BufferedImage cutImage(MultipartFile multipartFile, int imgWidth, int imgHeight){
        OperateImage operateImage = new OperateImage(0, 0,imgWidth,imgHeight);
        operateImage.setMultipartFile(multipartFile);
        try {
            return operateImage.cut();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 定时清理（每半小时）
     */
    @Scheduled(cron = "0 0/30 * * * ?")
    @Override
    public void regularlyCleaned(){
        File file=new File(path);
        File[] files = file.listFiles();
        if(files!=null&&files.length>0){
            for (File file1 : files) {
                Date when = new Date(System.currentTimeMillis() -  1000*60*30);
                if(new Date(file1.lastModified()).before(when)){
                    FileUtils.delete(file1);
                }
            }
        }
    }

    @Override
    public void deleteByName(String name) {
        FileUtils.delete(new File(path+"/"+name+".zip"));

    }
}
